<template>
  <div class="renttable businfosss">
    <div class="titletop">
      <div class="topbox newtopbox" style="width: 100%;padding-bottom: 3px">
        <span style="float: left;">租赁计划安排</span>
        <div style="float: right;margin-right: 20px;">
          <el-button
              @click="clearZero"
              size="small"
              :disabled="leaseInfo.payWay == 'DEBJ'"
              style="border:0"
              type="warning">
            一键清零
          </el-button>
        </div>
      </div>
    </div>
    <div style="font-size: 18px;height: 40px;line-height: 40px;text-align: left;padding-left: 20px">
      您的融资金额为：<span style="color: #ffc18d;font-size: 16px;">{{ leaseInfo.financeAmt }}</span>元
    </div>
    <el-table
        class="tables"
        :data="rentData"
        :summary-method="summaries"
        element-loading-text="加载中..."
        show-summary
        size="small"
        style="width: 100%;margin: 0 auto;font-size: 12px"
        :header-cell-style="{
                            'color': '#212121',
                            'font-size': '14px',
                            'font-weight': 'bold',
                            'background':'#eef1f6',
                            'line-hight':'40px',
                            'text-align': 'center',
                            'height':'40px'}"
        :cell-class-name="tableCellClassName"
        stripe
        border
    >
      <el-table-column
          :formatter="formatterPeriod"
          label="期数"
          prop="period">
      </el-table-column>
      <el-table-column
          label="本金(元)"
          prop="principal">
        <template slot-scope="scope">
          <el-input
              @change="changeVal"
              :disabled="leaseInfo.payWay == 'DEBJ' || scope.row.costType != 'rent' || scope.row.remark == 'discountEndDay'"
              v-model="scope.row.principal"></el-input>
        </template>
      </el-table-column>
      <el-table-column
          label="租赁利率(%)"
          prop="moneyRate">
        <template slot-scope="scope">
          <el-input
              :disabled="leaseInfo.payWay == 'DEBJ' || scope.row.costType != 'rent' || leaseInfo.leaseRateLock || scope.row.remark == 'discountEndDay'"
              @change="moneyRateChange"
              v-model="scope.row.moneyRate"></el-input>
        </template>
      </el-table-column>
      <el-table-column
          label="利息(元)"
          prop="interest">
      </el-table-column>
      <el-table-column
          label="租金总额(元)"
          prop="dueAmout">
      </el-table-column>
      <el-table-column
          label="支付日期"
          prop="dueDate">
      </el-table-column>
    </el-table>

    <div style="height: 60px;margin-top: 20px;text-align: center">
      <el-button @click="back">返回</el-button>
      <el-button style="margin-left: 50px" @click="calculate()" type="warning">重新计算</el-button>
      <el-button style="margin-left: 50px" @click="downloadRentTable" type="danger">下载租金计划表</el-button>
    </div>
  </div>
</template>

<script>
import componentitle from "@/components/title/title";
import {getStore} from "@/utils/utils";
import axios from "axios";

export default {
  name: "rentPlanTable",
  components: {
    componentitle,
  },
  props: {
    params: {
      type: Object
    }
  },
  data() {
    return {
      role: getStore('role') || '0',
      departId: getStore('departId') || '0',
      leaseInfo: this.params, //订单信息
      rentData: [],//租金流水信息
      testStatus: false,
      calcResult: {},
    }
  },
  created() {
    this.calculate();
  },
  methods: {
    changeVal() {
      this.testStatus = true;
    },
    moneyRateChange(val) {
      this.testStatus = true;
    },
    calculate() {
      if (this.rentData && this.rentData.length > 0) {
        let message = '';
        let totalAmt = 0;
        this.$xeUtils.arrayEach(this.rentData, item => {
          if (!item.principal && item.principal != '0') {
            message = '本金不允许为空，请重新填写';
          }
          if (!item.moneyRate && item.moneyRate != '0') {
            message = '利率不允许为空，请重新填写';
          }
          if (item.costType == 'rent') {
            totalAmt = totalAmt + this.$xeUtils.toNumber(item.principal);
          }
        });
        if (!message && totalAmt != this.leaseInfo.financeAmt) {
          message = '您的本金总金额与融资金额不一致';
        }
        if (message){
          this.$message.warning(message);
          return;
        }
      }
      const loading = this.$loading({
        lock: true,
        text: 'Loading',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      });
      const param = {
        orders: this.leaseInfo,
        principalList: this.rentData,
      };
      this.$post('/leaseinfo/calcTrial', param).then(res => {
        loading.close();
        this.testStatus = false;
        if (res.data.code == '2000000') {
          if (this.role == '1'){
            this.rentData = this.$xeUtils.filter(res.data.data.data, item=> item.costType != 'rebate' && item.costType != 'discount' && item.costType != 'otherexpense' && item.costType != 'agent_risk');
          } else {
            this.rentData = res.data.data.data;
          }
          this.calcResult = res.data.data.result;
          if (this.role == 0) {
            this.$message.success(`该笔业务的内部收益率为${this.mul(res.data.data.xirrTax, 100)}%`);
          } else {
            this.$message.success(`试算成功！`);
          }
          let msg = '';
          if (this.role == '1' && this.calcResult && (this.calcResult.discountAmt || this.calcResult.discountAmt == '0')){
            msg = '反推贴息为：'+this.calcResult.discountAmt+'元<br/>';
          }
          if (this.role == '1' && this.calcResult && (this.calcResult.otherExpenseAmt || this.calcResult.otherExpenseAmt == '0')){
            msg = msg + '赠送保险费用为：'+this.calcResult.otherExpenseAmt+'元';
          }
          if (msg){
            this.$alert(msg, '提示', {dangerouslyUseHTMLString : true});
          }
        }
      }).catch(() => {
        loading.close();
      });
    },
    clearZero() {
      this.changeVal();
      this.rentData.forEach(item => {
        item.principal = item.interest = item.dueAmout = 0;
      })
    },
    back() {
      this.$emit('back');
    },

    getMonthSpace(date1, date2) {
      if (!date1 || !date2) {
        return 0;
      }
      let year1 = this.$xeUtils.toDateString(date1, 'yyyy') * 1;
      let year2 = this.$xeUtils.toDateString(date2, 'yyyy') * 1;
      let month1 = this.$xeUtils.toDateString(date1, 'M') * 1;
      let month2 = this.$xeUtils.toDateString(date2, 'M') * 1;
      let day1 = this.$xeUtils.toDateString(date1, 'd') * 1;
      let day2 = this.$xeUtils.toDateString(date2, 'd') * 1;
      let yearInterval = year1 - year2;
      if (month1 < month2 || (month1 == month2 && day1 <= day2)) {
        yearInterval = yearInterval - 1;
      }
      let monthInterval = (month1 + 12) - month2;
      if (day1 > day2) {
        monthInterval = monthInterval + 1;
      }
      if (monthInterval % 12 == 0) {
        monthInterval = 12;
      } else {
        monthInterval = monthInterval % 12;
      }
      return yearInterval * 12 + monthInterval;
    },
    downloadRentTable() {
      if (this.testStatus) {
        this.$message.error('请先重新计算！');
        return;
      }
      const baseInfoList = [];
      baseInfoList.push('融资金额：' + this.leaseInfo.financeAmt + '元');
      const startDate = this.leaseInfo.startDate;
      let endDate = this.leaseInfo.endDate;
      baseInfoList.push('计划起租日：' + startDate);
      const endRentData = this.$xeUtils.find(this.rentData, item => item.costType == 'retain');
      if (endRentData && endRentData.dueDate){
        endDate = endRentData.dueDate;
      }
      baseInfoList.push('计划截止日：' + endDate);
      if (endDate && startDate){
        const limitMonth = this.getMonthSpace(endDate, startDate);
        baseInfoList.push('融资期限：' + limitMonth + '个月');
      }
      baseInfoList.push('租金支付方式：' + (this.leaseInfo.payWay == 'DEBJ' ? '等额本金' : '约定本金'));
      baseInfoList.push('还款频率：' + (this.leaseInfo.repayRate == 'S' ? '季度' : '月'));
      if (this.leaseInfo.smallAmount){
        baseInfoList.push('小额还本金额：' + this.leaseInfo.smallAmount + '元');
      }
      if (this.leaseInfo.bigAmtMonth){
        baseInfoList.push('大额还本时间：' + this.leaseInfo.bigAmtMonth);
      }
      let leaseRate = this.leaseInfo.leaseRate;
      if (this.calcResult && (this.calcResult.leaseRate || this.calcResult.leaseRate == '0')){
        leaseRate = this.$xeUtils.round(this.$xeUtils.toNumber(this.calcResult.leaseRate) * 100, 2);
      }
      if (leaseRate || leaseRate == '0'){
        baseInfoList.push('租赁利率：' + leaseRate + '%');
      }
      if (this.calcResult && this.calcResult.discountEndDay){
        baseInfoList.push('贴息截止日：' + this.calcResult.discountEndDay);
      }
      const loading = this.$loading({
        lock: true,
        text: 'Loading',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      });
      const param = {
        baseInfoList,
        principalList: this.rentData,
      };
      axios({
        method: 'post',
        url: '/leaseinfo/downloadCalcFile',
        data: param,
        responseType: 'blob' // 表明返回服务器返回的数据类型
      }).then((res) => { // 处理返回的文件流
        loading.close();
        const data = res.data
        const that = this;
        // 判断返回的文件类型是否为blob类型
        if (res.config.responseType == 'blob') {
          // 判断响应头里面是否包含后台返回的信息
          if (res.data.size == 0 || res.headers['content-type'].includes('json')) {
            // 通过FileReader把blob对象解析成json对象
            let fileReader = new FileReader();
            fileReader.readAsText(res.data);
            fileReader.onload = function (result) {
              let jsondata = JSON.parse(result.target.result);
              that.$message.warning(jsondata.msg);
            }
          } else {
            const blob = new Blob([data], {type: 'application/vnd.ms-excel;charset=utf-8'});
            const fileName =  '租金计划还款表.xlsx';
            // 非IE下载
            if ('download' in document.createElement('a')) {
              const elink = document.createElement('a');
              elink.download = fileName;
              elink.style.display = 'none';
              elink.href = URL.createObjectURL(blob);
              document.body.appendChild(elink);
              elink.click();
              URL.revokeObjectURL(elink.href);
              document.body.removeChild(elink);
            } else {
              // 兼容ie11
              if (window.navigator && window.navigator.msSaveOrOpenBlob) {
                try {
                  window.navigator.msSaveOrOpenBlob(blob, fileName);
                } catch (e) {
                  console.log(e);
                }
                return
              } else {// IE10+下载
                window.navigator.msSaveBlob(blob, fileName);
              }
            }
          }
        }
      }).catch((error) => {
        loading.close();
      });
    },
    formatterPeriod(row, column) {
      let obj = {
        rent: "租金",
        retain: "留购价",
        rebate: "经销商贴息",
        discount: "厂商贴息",
        agent_risk: "其他风险金",
        rent_risk: "承租人风险金",
        otherexpense: "保险费用",
      };

      if (row.costType !== 'rent') {
        return obj[row.costType];
      } else {
        return row.period;
      }
    },
    add(arg1, arg2) {
      let r1, r2, m;
      try {
        r1 = arg1.toString().split(".")[1].length;
      } catch (e) {
        r1 = 0
      }
      try {
        r2 = arg2.toString().split(".")[1].length;
      } catch (e) {
        r2 = 0
      }
      m = Math.pow(10, Math.max(r1, r2))
      return (this.mul(arg1, m) + this.mul(arg2, m)) / m
    },
    mul(arg1, arg2) { //js乘法
      let m = 0, s1 = arg1.toString(), s2 = arg2.toString();
      try {
        m += s1.split(".")[1].length
      } catch (e) {
      }
      try {
        m += s2.split(".")[1].length
      } catch (e) {
      }
      return Number(s1.replace(".", "")) * Number(s2.replace(".", "")) / Math.pow(10, m)
    },
    summaries(param) {
      const {columns, data} = param;
      const sums = [];
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = '总价';
          return;
        }
        if (index === 2) {
          return;
        }
        const values = data.map(item => Number(item[column.property]));
        if (!values.every(value => isNaN(value))) {
          sums[index] = values.reduce((prev, curr) => {
            const value = Number(curr);
            if (!isNaN(value)) {
              return this.add(prev, curr);
            } else {
              return prev;
            }
          }, 0);
        }
      });
      return sums;
    },
    tableCellClassName({row}) {
      if (row.remark && row.remark.indexOf('discountEndDay') >= 0) {
        return 'warning-cell';
      }
      return '';
    },
  },
  computed: {},
}
</script>

<style lang="less" scoped>
::v-deep .el-table .warning-cell {
  background-color: #E6A23C !important;
}
</style>